package com.sq.partner.manager.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.dao.GatewayChannelDemandConfigDao;
import com.sq.partner.manager.dao.ICoreDeptDao;
import com.sq.partner.manager.dao.IFacadeUserChannelDao;
import com.sq.partner.manager.dao.IGatewayAppTranstypeDao;
import com.sq.partner.manager.dao.IGatewayChannelAppDao;
import com.sq.partner.manager.dao.IGatewayChannelInfoConfigDao;
import com.sq.partner.manager.dao.IGatewayChannelIpDao;
import com.sq.partner.manager.dao.IGatewayChannelTranstypeDao;
import com.sq.partner.manager.dao.IGatewayChannelUserDao;
import com.sq.partner.manager.dao.IGatewaySubChannelDao;
import com.sq.partner.manager.dao.IGatewayTradInsuPlanDao;
import com.sq.partner.manager.dao.INlifePlanDao;
import com.sq.partner.manager.dao.ITradNoCarProdPlanDao;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.DictAddrDto;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayAppTranstype;
import com.sq.partner.manager.mybatis.model.GatewayChannelApp;
import com.sq.partner.manager.mybatis.model.GatewayChannelDemandConfig;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayChannelIp;
import com.sq.partner.manager.mybatis.model.GatewayChannelTranstype;
import com.sq.partner.manager.mybatis.model.GatewayChannelUser;
import com.sq.partner.manager.mybatis.model.GatewaySubChannel;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.NlifePlan;
import com.sq.partner.manager.mybatis.model.TradInsuPlan;
import com.sq.partner.manager.mybatis.model.TreeDto;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewayClearCacheManager;
import com.sq.partner.manager.util.ExcelUtil;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;

/**
 * 
 * @author duguangwei
 *
 */
@Service
public class GatewayChannelInfoConfigServiceImpl implements IGatewayChannelInfoConfigService {
	private static Logger logger = LogUtil.getLog(GatewayChannelInfoConfigServiceImpl.class); 
	@Resource
	private IGatewayChannelInfoConfigDao channelInfoConfigDao;
	@Resource
	private IGatewayChannelUserDao channelUserDao;
	@Resource
	private IGatewayChannelIpDao channelIpDao;
	@Resource
	private IGatewayChannelTranstypeDao channelTranstypeDao;
	@Resource
	private IGatewayAppTranstypeDao appTranstypeDao;
	@Resource
	IGatewayClearCacheManager gatewayClearCacheManager;
	@Resource
	IGatewayChannelInfoConfigDao gatewayChannelInfoConfigDao;
	@Resource
	IGatewayChannelAppDao gatewayChannelAppDao;
	@Resource
	IGatewaySubChannelDao gatewaySubChannelDao;
	@Resource
	private ICoreDeptDao deptDao;
	@Resource 
	IGatewayTradInsuPlanDao gatewayTradInsuPlanDao;
	@Resource 
	ITradNoCarProdPlanDao tradNoCarProdPlanDao;
	@Resource 
	private INlifePlanDao nlifePlanDao;
	
	@Resource
	private IFacadeUserChannelDao facadeUserChannelDao; 
	
	@Resource
	private GatewayChannelDemandConfigDao gatewayChannelDemandConfigDao;
	
	public Page getListByAppid(String appId) throws Exception {
		Page page=new Page();
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setFkAppid(appId);
		page.setData(channelInfoConfigDao.getValidListByAppid(channelInfo));
		return page;
	}
	@Override
	public Page<GatewayChannelInfo> getListByDept(Page<GatewayChannelInfo> page)
			throws Exception {
		page.setData(channelInfoConfigDao.getListByDept(page.getType()));
		return page;
	}
	@Override
	public Page getList(Page page) throws Exception {
		if(page.getSize() > 0 && page.getCurrent() > 0){
			Integer pageSize = page.getSize();
			Integer start = (page.getCurrent()-1)*pageSize;
		}
		return page;
	}


	@Override
	public Page getTranstypeBychannelCode(String channel_Code,String appid,String application) throws Exception {
		Page page=new Page();
		GatewayChannelTranstype gatewayChannelInfo = new GatewayChannelTranstype();
		gatewayChannelInfo.setFkChannelCode(channel_Code);
		gatewayChannelInfo.setAppId(appid);
		gatewayChannelInfo.setApplication(application);
		page.setData(channelInfoConfigDao.getTranstypeBychannelCode(gatewayChannelInfo));
		return page;
	}
	@Override
	public Page loadTransNameByApplication(String appid,String channel_Code) throws Exception {
		Page page=new Page();
		GatewayChannelTranstype gatewayChannelInfo = new GatewayChannelTranstype();
		gatewayChannelInfo.setAppId(appid);
		gatewayChannelInfo.setFkChannelCode(channel_Code);
		page.setData(channelInfoConfigDao.loadTransNameByApplication(gatewayChannelInfo));
		return page;
	}
	@Override
	public Page loadTransNameByApplication1(String appid) throws Exception {
		Page page=new Page();
		GatewayChannelTranstype gatewayChannelInfo = new GatewayChannelTranstype();
		gatewayChannelInfo.setAppId(appid);
		page.setData(channelInfoConfigDao.loadTransNameByApplication1(gatewayChannelInfo));
		return page;
	}
	@Override
	public Page queryByCriteria(Integer pageIndex,
			GatewayChannelInfo channelInfo,GatewayUser user) throws Exception{

		return channelInfoConfigDao.queryByCriteria(pageIndex, channelInfo, user);
	}
	@Override
	public Page<Map<String,Object>> queryByCriteria1(Integer pageIndex,Integer size,GatewayChannelInfo channelInfo,GatewayUser user,String businessChannelType) throws Exception{
		
		return channelInfoConfigDao.queryByCriteria1(pageIndex, size,channelInfo, user,businessChannelType);
	}

	@Override
	public Result deleteChannelInfoByChannelCode(GatewayChannelInfo channelInfo)
			throws Exception {
		
		int count = facadeUserChannelDao.queryUcCountByChannelCode(channelInfo.getChannelCode());
		if(count>0){
			return Result.error("已有出单用户配置该合作伙伴，不能删除");
		}
		//检查该合作伙伴是否有方案关联人险
		if(gatewayTradInsuPlanDao.isHasExistPlan(channelInfo.getChannelCode())){
			return Result.error("已有人险方案配置该合作伙伴，不能删除");
		}
		//检查该合作伙伴是否有方案关联新意健险
		if(nlifePlanDao.isHasExistNlifePlan(channelInfo.getChannelCode())){
			return Result.error("已有新意健险方案配置该合作伙伴，不能删除");
		}
		//检查该合作伙伴是否有方案关联财险
//		if(tradNoCarProdPlanDao.isHasExistPlan(channelInfo.getChannelCode())){
//			return Result.error("已有财险方案配置该合作伙伴，不能删除");
//		}
		//检查该合作机构是否存在非顶级子机构信息
		List<GatewaySubChannel> gsc = gatewaySubChannelDao.querySubChannelByParentCode(channelInfo.getChannelCode());
		if(gsc.size()>0)
		{
			return Result.error("该合作伙伴存在子机构配置，不能删除");
		}
		//检查应用信息
		List<GatewayChannelApp> gcaList = gatewayChannelAppDao.queryChannelAppInfoListByChannelCode(channelInfo.getChannelCode());
		if(gcaList.size()>0)
		{
			return Result.error("删除失败，请先删除关联的应用数据");
		}
		GatewayChannelUser channelUser = new GatewayChannelUser();
		channelUser.setFkChannelCode(channelInfo.getChannelCode());
		List<GatewayChannelUser> channelUserList = channelUserDao.queryByChannelUser(channelUser);
		if(channelUserList.size()>0)
		{
			return Result.error("删除失败，请先删除关联的用户数据");
		}
		GatewayChannelIp channelIp = new GatewayChannelIp();
		channelIp.setFkChannelCode(channelInfo.getChannelCode());
		List<GatewayChannelIp> channelIpList = channelIpDao.queryByChannelIp(channelIp);
		if(channelIpList.size() > 0){
			return Result.error("删除失败，请先删除关联的IP数据");
		}
		// 删除默认的顶级机构信息
		gatewaySubChannelDao.delDefaultSubChannel(channelInfo.getChannelCode());
		//物理删除
		channelInfoConfigDao.deleteByChannelCode(channelInfo.getChannelCode()); 
		//虚拟删除
//		channelInfo.setStatus("0");
//		channelInfoConfigDao.update(channelInfo);
		//清理缓存
		clearAllCacheByChannelCode(channelInfo.getChannelCode());
		return Result.success("删除成功");
	}

	@Override
	public void updateChannelAppId(GatewayChannelInfo channelInfo)
			throws Exception {
		channelInfoConfigDao.updateChannelAppId(channelInfo);
	}

	@Override
	public void saveOrUpdateChannelInfo(GatewayChannelInfo channelInfo,String flag) throws Exception {
		if(flag.equals("save")){
			channelInfo.setUuidFlag(generateShortUuid());
			channelInfoConfigDao.save(channelInfo);
		} else if (flag.equals("update")){
			
			channelInfoConfigDao.update(channelInfo);
		}
		clearAllCacheByChannelCode(channelInfo.getChannelCode());
	}
	@Override
	public void saveOrUpdateChannelInfoToURL(GatewayChannelInfo channelInfo,String flag) throws Exception {
		if(flag.equals("save")){
			channelInfo.setUuidFlag(generateShortUuid());
			channelInfoConfigDao.save(channelInfo);
		} else if (flag.equals("update")){
			
			channelInfoConfigDao.updateToURL(channelInfo);
		}
		clearAllCacheByChannelCode(channelInfo.getChannelCode());
	}
    public  String[] chars = new String[] { "a", "b", "c", "d", "e", "f",  
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",  
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",  
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",  
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",  
            "W", "X", "Y", "Z" };
	public String generateShortUuid() {  
		StringBuffer shortBuffer = new StringBuffer();  
		String uuid = UUID.randomUUID().toString().replace("-", "");  
		for (int i = 0; i < 8; i++) {  
		    String str = uuid.substring(i * 4, i * 4 + 4);  
		    int x = Integer.parseInt(str, 16);  
		    shortBuffer.append(chars[x % 0x3E]);  
		}  
		return shortBuffer.toString();  
	}  
	@Override
	public GatewayChannelInfo queryChannelInfoByChannelCode(String channelCode)
			throws Exception {
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setChannelCode(channelCode);
		GatewayChannelInfo channelInfoFind = channelInfoConfigDao.queryByChannelInfo(channelInfo);
		return channelInfoFind;
	}

	@Override
	public List<GatewayChannelUser> queryChannelUserByFkChannelCode(
			String fkChannelCode, String appid) throws Exception {
		GatewayChannelUser channelUser = new GatewayChannelUser();
		channelUser.setFkChannelCode(fkChannelCode);
		channelUser.setAppId(appid);
		List<GatewayChannelUser> channelUserList = channelUserDao.queryByChannelUser(channelUser);
		return channelUserList;
	}

	@Override
	public void delChannelUserByChannelUser(GatewayChannelUser channelUser)
			throws Exception {
		channelUserDao.delByChannelUser(channelUser);
		clearAllCacheByChannelCode(channelUser.getFkChannelCode());
 	}

	@Override
	public GatewayChannelUser queryChannelUserByChannelUser(
			GatewayChannelUser channelUser) throws Exception {
		List<GatewayChannelUser> channelUserList = channelUserDao.queryByChannelUser(channelUser);
		GatewayChannelUser user = null;
		for (GatewayChannelUser cu : channelUserList) {
			user = cu;
		}
		return user;
	}

	@Override
	public void saveChannelUser(GatewayChannelUser channelUser)
			throws Exception {
		channelUserDao.save(channelUser);
		//清除缓存
		clearAllCacheByChannelCode(channelUser.getFkChannelCode());
	}

	@Override
	public List<GatewayChannelIp> queryChannelIpByChannelIp(
			GatewayChannelIp channelIp) throws Exception {
		List<GatewayChannelIp> channelIpList = channelIpDao.queryByChannelIp(channelIp);
		return channelIpList;
	}

	@Override
	public void delChannelIpByChannelIp(GatewayChannelIp channelIp)
			throws Exception {
		channelIpDao.delByChannelIp(channelIp);
		//清除缓存
		clearAllCacheByChannelCode(channelIp.getFkChannelCode());
	}

	@Override
	public void saveChannelIp(GatewayChannelIp channelIp) throws Exception {
		channelIpDao.save(channelIp);
		
		//清除缓存
		clearAllCacheByChannelCode(channelIp.getFkChannelCode());
	}

	@Override
	public List<GatewayChannelTranstype> queryChannelTranstypeByChannelTranstype(
			GatewayChannelTranstype channelTranstype) throws Exception {
		List<GatewayChannelTranstype> channelTranstypeList = channelTranstypeDao.queryByChannelTranstype(channelTranstype);
		return channelTranstypeList;
	}

	@Override
	public List<GatewayAppTranstype> queryNotUsedAppTranstype(
			GatewayChannelInfo channelInfo) throws Exception {
		List<GatewayAppTranstype> appTranstypeList =appTranstypeDao.queryNotUsedAppTranstype(channelInfo);
		return appTranstypeList;
	}

	@Override
	public void delChannelTranstypeByChannelTranstype(
			Long transtypeId,String channelCode) throws Exception {
		channelTranstypeDao.delByChannelTranstype(transtypeId);
		clearAllCacheByChannelCode(channelCode);
	}

	@Override
	public void saveChannelTranstype(GatewayChannelTranstype channelTranstype)
			throws Exception {
		channelTranstypeDao.save(channelTranstype);
		//清除缓存
		clearAllCacheByChannelCode(channelTranstype.getFkChannelCode());	
	}


	@Override
	public List<TreeDto> queryBranchDeptOfOneUser(GatewayUser user) throws Exception {
		List<TreeDto> deptTree = deptDao.queryDeptOfOneUser(user);
		return deptTree;
	}
	//查询省市县三级联动方法
	@Override
	public List<DictAddrDto> queryProvinceCityCounty(DictAddrDto dictAddr) throws Exception {
		// TODO Auto-generated method stub
		List<DictAddrDto> dictAddrList = channelInfoConfigDao.queryProvinceCityCounty(dictAddr);
		return dictAddrList;
				
	}
	//查询企业类型和行业类型二级联动方法
	@Override
	public List<DictDto> querySubElementList(DictDto dict) throws Exception {
		// TODO Auto-generated method stub
		List<DictDto> dictList = channelInfoConfigDao.querySubElementList(dict);
		return dictList;
	}
	@Override
	public void delTransTypeByChannelCodeAndAppId(GatewayChannelTranstype gct)
			throws Exception {
		// TODO Auto-generated method stub
		channelTranstypeDao.delTransTypeByChannelCodeAndAppId(gct);
		clearAllCacheByChannelCode(gct.getFkChannelCode());	
	}
	@Override
	public Page queryAppInfoByChannelCode(Integer pageIndex, String channelCode)
			throws Exception {
		// TODO Auto-generated method stub
		return channelInfoConfigDao.queryAppInfoByChannelCode(pageIndex, channelCode);
	}
	
	// 检查用户是否有权限操作该合作伙伴
	public boolean checkIsHasPrivilege(HttpSession session, String deptCode) throws Exception {
		GatewayUser user = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
		//权限验证增加若当前用户角色中有总行机构则当前的用户则无需验证权限;
		if (StrUtil.isNotEmpty(user.getDepartmentStr())){
			if(user.getDepartmentStr().contains(Constants.HQ_BRANCH_CODE)){
				return true;
			}
		}
		String str=user.getDepartmentStr();
		String userDept="";
		if(StrUtil.isNotEmpty(str)){
			String[] depts= str.split(",");
			for (String string : depts) {
				userDept+=" union select  "+ string+ " from dual";
			}
		}
		if (StrUtil.isNotEmpty(user.getDepartmentStr()) && StrUtil.isNotEmpty(deptCode)) {
			//对于非总行部门的人员进行权限验证
			CoreDept cd = new CoreDept();
			cd.setUserPrivilegeDeptCode( " SELECT DEPT_CODE FROM T_CORE_DEPT WHERE DEPT_CODE LIKE '00%' " +userDept);
			cd.setDeptCode(deptCode);
			return deptDao.checkIsHasPrivilegeDept(cd);
		}
		return false;
	}
	
	//合作伙伴配置缓存管理公共方法
	public void clearAllCacheByChannelCode(String channelCode) throws Exception {
		//查询应用by：channelCode
		List<GatewayChannelApp> appLs = gatewayChannelAppDao.queryChannelAppInfoListByChannelCode(channelCode);
		if(null!=appLs && appLs.size()>0){
			for(GatewayChannelApp tem :appLs){
				gatewayClearCacheManager.clearAllCache(tem.getAppId());
			}
		}
	}
	
	//合作伙伴配置缓存管理公共方法扩展 clearBychannelCode 的集合
	public void clearAllCacheByChannelCodeExtend(List<TradInsuPlan> tradInsuPlanLists) throws Exception {
		//检测tradInsuPlanLists 大小以便逻辑判断
		if(tradInsuPlanLists.size()>1){
			List<String> beClearls = new ArrayList<String>();
			for(int i=0;i<tradInsuPlanLists.size();i++){
				List<GatewayChannelApp> appLs = gatewayChannelAppDao.queryChannelAppInfoListByChannelCode(tradInsuPlanLists.get(i).getPartnerNo());
				//对于集合中的第一个合作伙伴操作
				if(null != appLs && appLs.size() > 0 && 0==i){
					for (int j = 0;j<appLs.size();j++) {
							gatewayClearCacheManager.clearAllCache(appLs.get(j).getAppId());
							beClearls.add(appLs.get(j).getAppId());
						}
				}else if(null != appLs && appLs.size() > 0 && i>0){
					for (int j = 0;j<appLs.size();j++) {
						if(!beClearls.contains(appLs.get(j).getAppId())){
							gatewayClearCacheManager.clearAllCache(appLs.get(j).getAppId());
							beClearls.add(appLs.get(j).getAppId());
						}
					}
				}
			}
			beClearls=null;
		} else {
			List<GatewayChannelApp> appLs = gatewayChannelAppDao.queryChannelAppInfoListByChannelCode(tradInsuPlanLists.get(0).getPartnerNo());
			if (null != appLs && appLs.size() > 0) {
				for (GatewayChannelApp tem : appLs) {
					gatewayClearCacheManager.clearAllCache(tem.getAppId());
				}
			}
		}
	}
	@Override
	public Page<GatewayChannelInfo> getChannelInfoListByDeptCode(Page<GatewayChannelInfo> page) throws Exception {
		// TODO Auto-generated method stub
		return channelInfoConfigDao.getChannelInfoListByDeptCode(page);
	}
	@Override
	public void clearAllNewLifeCacheByChannelCodeExtend(List<NlifePlan> tradInsuPlanLists) throws Exception {
		//检测tradInsuPlanLists 大小以便逻辑判断
		if(tradInsuPlanLists.size()>1){
			List<String> beClearls = new ArrayList<String>();
			for(int i=0;i<tradInsuPlanLists.size();i++){
				List<GatewayChannelApp> appLs = gatewayChannelAppDao.queryChannelAppInfoListByChannelCode(tradInsuPlanLists.get(i).getPartnerNo());
				//对于集合中的第一个合作伙伴操作
				if(null != appLs && appLs.size() > 0 && 0==i){
					for (int j = 0;j<appLs.size();j++) {
							gatewayClearCacheManager.clearAllCache(appLs.get(j).getAppId());
							beClearls.add(appLs.get(j).getAppId());
						}
				}else if(null != appLs && appLs.size() > 0 && i>0){
					for (int j = 0;j<appLs.size();j++) {
						if(!beClearls.contains(appLs.get(j).getAppId())){
							gatewayClearCacheManager.clearAllCache(appLs.get(j).getAppId());
							beClearls.add(appLs.get(j).getAppId());
						}
					}
				}
			}
			beClearls=null;
		} else {
			List<GatewayChannelApp> appLs = gatewayChannelAppDao.queryChannelAppInfoListByChannelCode(tradInsuPlanLists.get(0).getPartnerNo());
			if (null != appLs && appLs.size() > 0) {
				for (GatewayChannelApp tem : appLs) {
					gatewayClearCacheManager.clearAllCache(tem.getAppId());
				}
			}
		}
	}
	
	@Override
	public List<TreeDto> querySubChannelTreeByParentChannelCode(
							String parentChannelCode) throws Exception{
		return channelInfoConfigDao.querySubChannelTreeByParentChannelCode(parentChannelCode);
	}
	@Override
	public Page<GatewayChannelDemandConfig> queryDemandList(
			Page<GatewayChannelDemandConfig> page) throws Exception {
		Page<GatewayChannelDemandConfig> data = gatewayChannelDemandConfigDao.queryDemandPage(page);
		return data;
	}
	@Override
	public String insertChannelDemands(List<GatewayChannelDemandConfig> list){
			ArrayList<GatewayChannelDemandConfig> costList = new ArrayList<GatewayChannelDemandConfig>();
			try {
				gatewayChannelDemandConfigDao.insertDemands(list);
				for (GatewayChannelDemandConfig gatewayChannelDemandConfig : list) {
					GatewayChannelDemandConfig cost = new GatewayChannelDemandConfig();
					cost.setId(gatewayChannelDemandConfig.getId());
					cost.setSystemCode("PARTNERSYSTEM");
					cost.setChannelCost(gatewayChannelDemandConfig.getPartnerSystem());
					cost.setOperUser(gatewayChannelDemandConfig.getOperUser());
					cost.setOperTime(gatewayChannelDemandConfig.getOperTime());
					cost.setSystemName("合作伙伴系统");
					costList.add(cost);
					GatewayChannelDemandConfig cost1 = new GatewayChannelDemandConfig();
					cost1.setId(gatewayChannelDemandConfig.getId());
					cost1.setSystemCode("NLIFESYSTEM");
					cost1.setChannelCost(gatewayChannelDemandConfig.getNlifeSystem());
					cost1.setOperUser(gatewayChannelDemandConfig.getOperUser());
					cost1.setOperTime(gatewayChannelDemandConfig.getOperTime());
					cost1.setSystemName("新意健险系统");
					costList.add(cost1);
					GatewayChannelDemandConfig cost2 = new GatewayChannelDemandConfig();
					cost2.setId(gatewayChannelDemandConfig.getId());
					cost2.setSystemCode("COREFIVE");
					cost2.setChannelCost(gatewayChannelDemandConfig.getCoreFive());
					cost2.setOperUser(gatewayChannelDemandConfig.getOperUser());
					cost2.setOperTime(gatewayChannelDemandConfig.getOperTime());
					cost2.setSystemName("核心V5");
					costList.add(cost2);
					GatewayChannelDemandConfig cost3 = new GatewayChannelDemandConfig();
					cost3.setId(gatewayChannelDemandConfig.getId());
					cost3.setSystemCode("CORESEVEN");
					cost3.setChannelCost(gatewayChannelDemandConfig.getCoreSeven());
					cost3.setOperUser(gatewayChannelDemandConfig.getOperUser());
					cost3.setOperTime(gatewayChannelDemandConfig.getOperTime());
					cost3.setSystemName("核心V7");
					costList.add(cost3);
					GatewayChannelDemandConfig cost4 = new GatewayChannelDemandConfig();
					cost4.setId(gatewayChannelDemandConfig.getId());
					cost4.setSystemCode("EPOLICYSYSTEM");
					cost4.setChannelCost(gatewayChannelDemandConfig.getePolicySystem());
					cost4.setOperUser(gatewayChannelDemandConfig.getOperUser());
					cost4.setOperTime(gatewayChannelDemandConfig.getOperTime());
					cost4.setSystemName("电子保单系统");
					costList.add(cost4);
				}
				for (GatewayChannelDemandConfig gatewayChannelDemandConfig : costList) {		
					gatewayChannelDemandConfigDao.addCost(gatewayChannelDemandConfig);
				}
				
			} catch (Exception e) {
				logger.info("添加失败", e);
				return "error";
			}
		return "success";
	
	}
	@Override
	public String insertVersion(
			GatewayChannelDemandConfig gatewayChannelDemandConfig) {
		int queryVersionExist = 0;
		try {
			queryVersionExist = gatewayChannelDemandConfigDao.queryVersionExist(gatewayChannelDemandConfig.getChannelVersion());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		if(queryVersionExist==0){
			try {
				gatewayChannelDemandConfigDao.addVersion(gatewayChannelDemandConfig);
				return "success";
			} catch (Exception e) {
				logger.info("添加失败", e);
				return "error";
			}
		}else{
			return "error";
		}
	}
	@Override
	public GatewayChannelDemandConfig queryDemandForUpdate(
			Map<String, Object> map) throws Exception {
		
		return gatewayChannelDemandConfigDao.selectDemandForUpdate(map);
	}
	@Override
	public boolean updateChannelDemand(GatewayChannelDemandConfig info)
			throws Exception {	
		return gatewayChannelDemandConfigDao.updateDemandByID(info);
	}
	@Override
	public String insertDemandCost(GatewayChannelDemandConfig config) {
		try {
			gatewayChannelDemandConfigDao.addCost(config);
		} catch (Exception e) {
			logger.info("添加失败", e);
			return "error";
		}
		return "success";
	}
	@Override
	public List<GatewayChannelDemandConfig> selectDemandList(
			Map<String, Object> map) throws Exception {
		return gatewayChannelDemandConfigDao.selectDemandCost(map);
	}
	@Override
	public List<InputStream> getFileInputStream(MultipartFile[] myfiles)
			throws AppException {
		List<InputStream> inputStreams=new ArrayList<InputStream>();
		try {
			for(MultipartFile file : myfiles){
				String fileNameStr = file.getOriginalFilename();
				int lastDotIndex = fileNameStr.lastIndexOf(".");
				if(-1==lastDotIndex){
					throw new AppException("请选择扩展名为 .xls 的文件上传");
				}else{
					String extName = fileNameStr.substring(lastDotIndex+1,fileNameStr.length());
					if(!"xls".equals(extName.toLowerCase())){
						throw new AppException("请选择扩展名为 .xls 的文件上传");
					}
				}
				if (file.isEmpty()) {
					throw new AppException("上传失败，上传文件不能为空！");
				} else {
					InputStream inputStream = file.getInputStream();
					inputStreams.add(inputStream);
				}
			}
		} catch (IOException e) {
			throw new AppException("上传错误!请稍后重试");
		}
		return inputStreams;
	}

	@Override
	public void importExcelForDemand(InputStream inputStream, GatewayUser user,
			HttpSession session,List<String> versionList) throws Exception {
		HSSFWorkbook workBook = null;
		List<GatewayChannelDemandConfig> list = null;
		int errorCount = 0;
		StringBuffer errorMsg = new StringBuffer();
		try {
			workBook = new HSSFWorkbook(inputStream);
			list = new ArrayList<GatewayChannelDemandConfig>();
		} catch (Exception e) {
			logger.info("上传失败，上传文件内容有误", e);
			throw new AppException("上传失败，上传文件内容有误!");
		}
		HSSFSheet sheet = workBook.getSheetAt(0);
		String sheetName = workBook.getSheetName(0);
		boolean flag = false;
		if (StrUtil.isNotEmpty(sheetName) && sheetName.contains("需求导入")) {
			flag = true;
		}
		int lastRow = 0;
		if (sheet != null) {
			lastRow = sheet.getLastRowNum();
		}
		if (lastRow > 4 && flag) {
			int count = sheet.getLastRowNum();
			for (int rowNum = 5; rowNum <= count; rowNum++) {
				HSSFRow hssfRow = sheet.getRow(rowNum);
				for (int colNum = 0; colNum < hssfRow.getLastCellNum(); colNum++) {
					if ((0 != colNum)&&(4 != colNum)&& (5 != colNum)&& (6 != colNum)&& (7 != colNum)&& (8 != colNum)&& (StrUtil.isEmpty(ExcelUtil.getCellText(hssfRow.getCell(colNum)).trim()))) {
						errorMsg.append("需求导入信息第" + (rowNum + 1)+ " 行数据未导入，原因：列数据为必录项不允许为空，请检查 <br>");
						errorCount++;
						continue;
					}
				}
				String partnerNumber = ExcelUtil.getCellText(hssfRow.getCell(0)).trim();
				String channelVersion = ExcelUtil.getCellText(hssfRow.getCell(1)).trim();
				if(!versionList.contains(channelVersion)){
					errorMsg.append("需求导入信息第" + (rowNum + 1)+ " 行数据未导入，原因：版本日期不存在，请检查 <br>");
					errorCount++;
				}
				if (errorCount > 10) {
					throw new AppException("上传失败:<br>" + errorMsg.toString());
				}
				String channelCode = ExcelUtil.getCellText(hssfRow.getCell(2)).trim();
				String demandName = ExcelUtil.getCellText(hssfRow.getCell(3)).trim();
				String partnerSystem = ExcelUtil.getCellText(hssfRow.getCell(4)).trim();
				String nlifeSystem = ExcelUtil.getCellText(hssfRow.getCell(5)).trim();
				String coreFive = ExcelUtil.getCellText(hssfRow.getCell(6)).trim();
				String coreSeven = ExcelUtil.getCellText(hssfRow.getCell(7)).trim();
				String ePolicySystem = ExcelUtil.getCellText(hssfRow.getCell(8)).trim();
				GatewayChannelDemandConfig demand = new GatewayChannelDemandConfig();
				demand.setPartnerNumber(partnerNumber);
				demand.setChannelCode(channelCode);
				demand.setChannelVersion(channelVersion);
				demand.setDemandName(demandName);
				if(partnerSystem != ""){
					demand.setPartnerSystem(new BigDecimal(partnerSystem));
				}
				if(nlifeSystem != ""){
					demand.setNlifeSystem(new BigDecimal(nlifeSystem));
				}
				if(coreFive != ""){
					demand.setCoreFive(new BigDecimal(coreFive));
				}
				if(coreSeven != ""){
					demand.setCoreSeven(new BigDecimal(coreSeven));
				}
				if(ePolicySystem != ""){
					demand.setePolicySystem(new BigDecimal(ePolicySystem));
				}
				demand.setOperUser(user.getUserCode());
				demand.setOperTime(new Date());
				list.add(demand);
			}
			if (StrUtil.isNotEmpty(errorMsg.toString())) {
				throw new AppException("上传失败:<br>" + errorMsg.toString());
			}
			if (list.size() > 0) {
				
				gatewayChannelDemandConfigDao.insertDemands(list);
				
				ArrayList<GatewayChannelDemandConfig> costList = new ArrayList<GatewayChannelDemandConfig>();
				for (GatewayChannelDemandConfig gatewayChannelDemandConfig : list) {
					GatewayChannelDemandConfig cost = new GatewayChannelDemandConfig();
					cost.setId(gatewayChannelDemandConfig.getId());
					cost.setSystemCode("PARTNERSYSTEM");
					cost.setChannelCost(gatewayChannelDemandConfig.getPartnerSystem());
					cost.setOperUser(gatewayChannelDemandConfig.getOperUser());
					cost.setOperTime(gatewayChannelDemandConfig.getOperTime());
					cost.setSystemName("合作伙伴系统");
					costList.add(cost);
					GatewayChannelDemandConfig cost1 = new GatewayChannelDemandConfig();
					cost1.setId(gatewayChannelDemandConfig.getId());
					cost1.setSystemCode("NLIFESYSTEM");
					cost1.setChannelCost(gatewayChannelDemandConfig.getNlifeSystem());
					cost1.setOperUser(gatewayChannelDemandConfig.getOperUser());
					cost1.setOperTime(gatewayChannelDemandConfig.getOperTime());
					cost1.setSystemName("新意健险系统");
					costList.add(cost1);
					GatewayChannelDemandConfig cost2 = new GatewayChannelDemandConfig();
					cost2.setId(gatewayChannelDemandConfig.getId());
					cost2.setSystemCode("COREFIVE");
					cost2.setChannelCost(gatewayChannelDemandConfig.getCoreFive());
					cost2.setOperUser(gatewayChannelDemandConfig.getOperUser());
					cost2.setOperTime(gatewayChannelDemandConfig.getOperTime());
					cost2.setSystemName("核心V5");
					costList.add(cost2);
					GatewayChannelDemandConfig cost3 = new GatewayChannelDemandConfig();
					cost3.setId(gatewayChannelDemandConfig.getId());
					cost3.setSystemCode("CORESEVEN");
					cost3.setChannelCost(gatewayChannelDemandConfig.getCoreSeven());
					cost3.setOperUser(gatewayChannelDemandConfig.getOperUser());
					cost3.setOperTime(gatewayChannelDemandConfig.getOperTime());
					cost3.setSystemName("核心V7");
					costList.add(cost3);
					GatewayChannelDemandConfig cost4 = new GatewayChannelDemandConfig();
					cost4.setId(gatewayChannelDemandConfig.getId());
					cost4.setSystemCode("EPOLICYSYSTEM");
					cost4.setChannelCost(gatewayChannelDemandConfig.getePolicySystem());
					cost4.setOperUser(gatewayChannelDemandConfig.getOperUser());
					cost4.setOperTime(gatewayChannelDemandConfig.getOperTime());
					cost4.setSystemName("电子保单系统");
					costList.add(cost4);
				}
				for (GatewayChannelDemandConfig gatewayChannelDemand : costList) {
					gatewayChannelDemandConfigDao.addCost(gatewayChannelDemand);
				}
			}

		}else{
			errorMsg.append("Excel内容为空 <br>");
			throw new AppException("上传失败:<br>" + errorMsg.toString());
		}
	}
	@Override
	public List<GatewayChannelDemandConfig> selectPartnerInfo(GatewayChannelDemandConfig info)
			throws Exception {
		
		return gatewayChannelDemandConfigDao.queryPartnerInfo(info);
	}
	@Override
	public List<GatewayChannelDemandConfig> selectVersionInfo(GatewayChannelDemandConfig info)
			throws Exception {
		return gatewayChannelDemandConfigDao.queryVersionInfo(info);
	}
	@Override
	public List<GatewayChannelDemandConfig> selectDemandInfo(GatewayChannelDemandConfig info) throws Exception {

		return gatewayChannelDemandConfigDao.queryDemandInfo(info);
	}
	@Override
	public boolean deleteChannelCosts(Map<String,Object>map)
			throws Exception {

		return gatewayChannelDemandConfigDao.deleteChannelCost(map);
	}
	@Override
	public boolean deleteChannelDemands(Map<String,Object>map)
			throws Exception {

		return gatewayChannelDemandConfigDao.deleteChannelDemand(map);
	}
	@Override
	public List<GatewayChannelDemandConfig> demandExportSelect(
			Map<String, Object> map) throws Exception {
		
		return gatewayChannelDemandConfigDao.demandExportSelect(map);
	}
	@Override
	public boolean updateDemandCost(GatewayChannelDemandConfig info)
			throws Exception {
		return gatewayChannelDemandConfigDao.updateDemandCostByID(info);
	}
	@Override
	public int queryVersionExist(String channelVersion) throws Exception {
		
		return gatewayChannelDemandConfigDao.queryVersionExist(channelVersion);
	}
	@Override
	public List<String> queryDemandChannelCode(Map<String, Object> map)
			throws Exception {
		
		return gatewayChannelDemandConfigDao.queryChannelCodeByParameter(map);
	}
	@Override
	public String queryIfInternetPlan(String partnerCode) throws Exception {
		return gatewayChannelInfoConfigDao.queryIfInternetPlan(partnerCode);
	}
}
